﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Coravel.Invocable;
using CRM.Extensions;
using CRM.Models.Email;
using CRM.Services.Email;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace CRM.Jobs
{
    public class TrackReadEmailJob : IInvocable
    {
        private readonly MyDbContext _dbContext;
        private readonly ILogger<TrackReadEmailJob> _logger;
        private readonly RushMailApplicationService _rushMailApplicationService;

        public TrackReadEmailJob( MyDbContext dbContext, ILogger<TrackReadEmailJob> logger, RushMailApplicationService rushMailApplicationService)
        {
            _dbContext = dbContext;
            _logger = logger;
            _rushMailApplicationService = rushMailApplicationService;
        }
        public async Task Invoke()
        {
            // 超时任务取消跟踪
            var last7days = DateTime.Now.AddDays(-7);
            var needToEndTrack =  await _dbContext.RushMailLinks.Include(link => link.EmailMarketing)
                .Where(link => link.State == RushMailState.NeedTrack && link.EmailMarketing.CreatedAt < last7days)
                .ToArrayAsync();
            foreach (var link in needToEndTrack)
            {
                link.State = RushMailState.Completed;
            }
            await _dbContext.SaveChangesAsync();
            _logger.LogInformation("取消跟踪超时发送任务数量为: {Num}", needToEndTrack.Length);
            
            var needToTrack = await _dbContext.RushMailLinks
                .Where(m => m.State == RushMailState.NeedTrack && m.TaskId > 0) // 已完成
                .OrderBy(m => m.LatestTrackTime)
                .Take(10)
                .ToListAsync();
            _logger.LogInformation("准备跟踪发送任务数量为: {Num}", needToTrack.Count);
            foreach (var task in needToTrack)
            {
                await _rushMailApplicationService.TrackReadNum(task);
            }
        }
    }
}